let currentUser:API.UserShowMineResult | undefined;

export const setUserInfo = (user?: API.UserShowMineResult) => {
  if(user){
    window._hmt?.push([ '_setCustomVar', 1, 'userUuid', user.uuid, 1 ]);

    currentUser = user;
  }else{
    window._hmt?.push([ '_setCustomVar', 1, 'userUuid', '', 1 ]);

    currentUser=undefined;
  }
};

export const sendEvent = (param:{category: string;action: string;label: string;value?: any}) => {
  const arr = [ '_trackEvent', param.category, param.action, param.label ];
  if (param.value) {
    arr.push(param.value);
  }
  window._hmt?.push(arr);

  const send = ()=>{
    const sendParam:API.TrackCreateDto = {
      eventKey: `${param.action}-${param.category}`
    }
    if(param.value){
      sendParam.properties = param.value;
    }
    if(currentUser){
      sendParam.userUuid = currentUser.uuid;
    }
    const blob = new Blob([JSON.stringify(sendParam)], {type : 'application/json; charset=UTF-8'})
    window.navigator.sendBeacon('/api/v1/tracks',blob);
  };

  if(window.requestIdleCallback){
    window.requestIdleCallback(send)
  }else{
    send();
  }
};
